<?php

namespace app\radar\controller;

use app\ApiRest;
use app\card\model\CardCount;
use app\card\model\ClientInfo;
use app\card\model\Collection;
use app\card\model\User;
use app\card\model\UserFollow;
use app\card\model\UserPhone;
use app\radar\model\RadarAnswer;
use app\radar\model\RadarCard;
use app\radar\model\RadarCount;
use app\radar\model\RadarFollow;
use app\radar\model\RadarLabel;
use app\radar\model\RadarMessage;
use app\radar\model\RadarOrder;
use app\radar\model\RadarQuestionnaire;
use app\radar\model\RadarStart;
use app\radar\model\RadarUserLabel;
use app\radar\model\RadarUserMark;
use longbingcore\permissions\AdminMenu;
use longbingcore\tools\LongbingArr;
use think\App;
use think\facade\Db;

class IndexV2 extends ApiRest
{
    protected $modelCount;
    protected $modelCard;

    // 继承 验证用户登陆
    public function __construct ( App $app )
    {
        parent::__construct( $app );
        $this->modelCount = new RadarCount();
        $this->modelCard  = new RadarCard();
        //判断是否是员工
        $user = longbingGetUser($this->getUserId() ,$this->_uniacid);
        $user_info = longbingGetUserInfo($this->getUserId() ,$this->_uniacid);
        //不需要员工权限的接口
        $dont_need_check_actions = ['reportDuration' ,'reportData'];
        if((empty($user['is_staff']) || empty($user_info) || empty($user_info['is_staff'])) && !in_array($this->request->action(), $dont_need_check_actions))
        {
            echo json_encode($this->getErrorData(lang('you are not staff') ,403));
            die;
        }
    }

    /**
     * @Purpose: 员工端雷达线索列表
     *
     * @Param: $order number 排序方式 1 = 意向度 其他 = 最后访问时间
     *
     * @Method: GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function radarClue ()
    {
        $userId = $this->getUserId();
        $page   = isset( $this->_param[ 'page' ] ) ? $this->_param[ 'page' ] : 1;

        $verify = [ 'order' => 0, 'is_list' => 0 ];

        $params = lbGetParamVerify( $this->_param, $verify );

        $where   = [ [ 'a.to_uid', '=', $userId ] ];
        $where[] = [ 'a.uid', '<>', $userId ];


        if ( $params[ 'is_list' ] != 1 )
        {
            $where[] = [ 'a.intention', '<>', 1 ];
        }
        else
        {
            $where[] = [ 'a.intention', '=', 1 ];
        }

        $order = [ 'field' => 'b_time', 'way' => 'desc' ];

        if ( $params[ 'order' ] == 1 )
        {
            $order = [ 'field' => 'a.rate', 'way' => 'desc' ];
        }

        if ( $params[ 'order' ] == 2 )
        {
            $order = [ 'field' => 'a.update_time', 'way' => 'desc' ];
        }
        $data = $this->handleClientList( $where, $order, $page, $params, $userId );

        //  处理图片默认数据
        $data[ 'data' ] = formatDefaultImage( $data[ 'data' ], 'avatarUrl', 'avatar', $this->defaultImage );

        return $this->success( $data );
    }

    /**
     * @Purpose: 处理客户列表
     *
     * @Method: protected
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    protected function handleClientList ( $where, $order, $page, $params, $userId )
    {
        $data = Collection::alias( 'a' )
            ->field( [ 'a.*', 'b.id as b_id', 'b.create_time', 'max(b.create_time) as b_time',
                    'count(b.id) as b_count', 'c.nickName', 'c.avatarUrl', 'c.avatarUrl', 'c.import',
                    'c.gender','c.is_staff' ]
            )
            ->where( $where )
            ->leftJoin( 'longbing_card_count b', 'a.uid = b.user_id && a.to_uid = b.to_uid' )
            ->join( 'longbing_card_user c', 'a.uid = c.id' )
            ->order( $order[ 'field' ], $order[ 'way' ] )
            ->group( 'a.uid, a.to_uid' )
            ->paginate( [ 'list_rows' => 10, 'page' => $page ] )
            ->toArray();

        foreach ($data['data'] as $key => $val)
        {
            if(!isset($val['b_time']) || empty($val['b_time'])) $data['data'][$key]['b_time'] = $val['create_time'];
            if(empty($data['data'][$key]['b_time'])) $data['data'][$key]['b_time'] = $val['update_time'];
            $dis = [

                'user_id'  =>  $val['uid'],

                'staff_id' =>  $val['to_uid'],
            ];

            $data['data'][$key]['remark_name'] = Db::name('longbing_card_client_info')->where($dis)->value('name');
        }
        //  处理雷达展示日期
        $data[ 'data' ] = lbHandelRadarDate( $data[ 'data' ], 'b_time' );

        //  处理用户来源
        $data[ 'data' ] = lbHandelRadarSource( $data[ 'data' ] );

        //  client_source 用户来源 1 = 微信小程序 2 = 百度小程序 3 = 支付宝小程序 4 = 抖音小程序
        //  查询手机号
        $tmpArr = [];
        foreach ( $data[ 'data' ] as $index => $item )
        {
            $data[ 'data' ][ $index ][ 'phone' ]         = '';
            $data[ 'data' ][ $index ][ 'client_source' ] = 1;
            array_push( $tmpArr, $item[ 'uid' ] );

            // 客户列表相关数据
            if ( $params[ 'is_list' ] == 1 )
            {
                //  给客户打的标签
                $labelList = RadarUserLabel::alias( 'a' )
                    ->field( [ 'b.name' ] )
                    ->join( 'longbing_card_label b', 'a.label_id = b.id' )
                    // 注意这里的表明中的label和字段名label_id不一样，因为字段名取名取错了
                    ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.user_id', '=', $item[ 'uid' ] ],
                            [ 'a.status', '=', 1 ] ]
                    )
                    ->limit( 4 )
                    ->select()
                    ->toArray();

                $data[ 'data' ][ $index ][ 'labelList' ]  = $labelList;
                $data[ 'data' ][ $index ][ 'labelCount' ] = RadarUserLabel::alias( 'a' )
                    ->field( [ 'b.name' ] )
                    ->join( 'longbing_card_label b', 'a.label_id = b.id' )
                    // 注意这里的表明中的label和字段名label_id不一样，因为字段名取名取错了
                    ->where( [ [ 'a.staff_id', '=', $userId ],
                            [ 'a.user_id', '=', $item[ 'uid' ] ],
                            [ 'a.status', '=', 1 ] ]
                    )
                    ->count();


                $eventData = event("StaffCustomerList", $item );
                $eventData = LongbingArr::array_merge($eventData) ;
                //客户类别数据统计区域
                $data[ 'data' ][ $index ]['client_counts'] = $eventData ;
            }

        }
        if ( !empty( $tmpArr ) )
        {
            $tmpArr = array_unique( $tmpArr );

            $list = UserPhone::where( [ [ 'user_id', 'in', $tmpArr ] ] )
                ->field( [ 'user_id', 'phone' ] )
                ->select()
                ->toArray();

            $markList = RadarUserMark::where( [ [ 'user_id', 'in', $tmpArr ] ,['staff_id' ,'=' ,$userId]] )
                ->field( [ 'user_id', 'mark' ] )
                ->select()
                ->toArray();

            $tmpArr     = [];
            $tmpArrMark = [];

            foreach ( $list as $index => $item )
            {
                $tmpArr[ $item[ 'user_id' ] ] = $item[ 'phone' ];
            }

            foreach ( $markList as $index => $item )
            {
                $tmpArrMark[ $item[ 'user_id' ] ] = $item[ 'mark' ];
            }

            foreach ( $data[ 'data' ] as $index => $item )
            {
                $data[ 'data' ][ $index ][ 'mark' ] = 0;

                if ( isset( $tmpArr[ $item[ 'uid' ] ] ) )
                {
                    $data[ 'data' ][ $index ][ 'phone' ] = $tmpArr[ $item[ 'uid' ] ];
                }
                $data[ 'data' ][ $index ][ 'mark' ] = 0;
                if ( isset( $tmpArrMark[ $item[ 'uid' ] ] ) )
                {
                    $data[ 'data' ][ $index ][ 'mark' ] = $tmpArrMark[ $item[ 'uid' ] ];
                    if ( $tmpArrMark[ $item[ 'uid' ] ] == 2 && isset( $data[ 'data' ][ $index ][ 'labelCount' ] ) )
                    {
                        $data[ 'data' ][ $index ][ 'labelCount' ] += 1;
                    }
                }
            }
        }

        $data[ 'data' ] = formatDefaultImage( $data[ 'data' ], 'avatarUrl', 'avatar', $this->defaultImage );

        return $data;
    }




    /**
     * @Purpose: 标签客户列表
     *
     * @Param: $order number 排序方式 1 = 意向度 其他 = 最后访问时间
     *
     * @Method GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function labelClientList ()
    {
        $userId = $this->getUserId();

        $verify = [ 'label_id' => 0, 'mark' => 0, 'start' => 0, 'page' => 1, 'order' => 0, 'is_list' => 0 ];

        $params = lbGetParamVerify( $this->_param, $verify );

        //        $where   = [ [ 'a.to_uid', '=', $userId ] ];
        $where   = [ 'a.uid', '<>', $userId ];
        $where[] = [ 'd.staff_id', '=', $userId ];

        $order = [ 'field' => 'b_time', 'way' => 'desc' ];

        if ( $params[ 'order' ] == 1 )
        {
            $order = [ 'field' => 'c.rate', 'way' => 'desc' ];
        }

        //  查询新标客户
        if ( $params[ 'start' ] == 1 )
        {

            $data = RadarStart::alias( 'a' )
                ->field( [ 'd.id as b_id', 'd.create_time', 'max(d.create_time) as b_time',
                        'count(d.id) as b_count', 'b.nickName', 'b.avatarUrl', 'b.avatarUrl', 'b.import',
                        'b.gender', 'c.*' ]
                )
                ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.status', '=', 1 ] ] )
                ->join( 'longbing_card_user b', 'a.user_id = b.id' )
                ->join( 'longbing_card_collection c', 'a.user_id = c.uid && c.to_uid = a.staff_id' )
                ->join( 'longbing_card_count d', 'a.user_id = d.user_id && a.staff_id = d.to_uid','left' )
                ->order( $order[ 'field' ], $order[ 'way' ] )
                ->group( 'a.user_id, a.staff_id' )
                ->paginate( [ 'list_rows' => 10, 'page' => $params[ 'page' ] ] )
                ->toArray();

        }
        //  已成交的客户
        else if ( $params[ 'mark' ] == 1 )
        {
            $data = RadarUserMark::alias( 'a' )
                ->field( [ 'd.id as b_id', 'd.create_time', 'max(d.create_time) as b_time',
                        'count(d.id) as b_count', 'b.nickName', 'b.avatarUrl', 'b.avatarUrl', 'b.import',
                        'b.gender', 'c.*','b.is_staff' ]
                )
                ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.user_id', '<>', $userId ],
                        [ 'a.status', '=', 1 ], [ 'mark', '=', 2 ] ]
                )
                ->join( 'longbing_card_user b', 'a.user_id = b.id' )
                ->join( 'longbing_card_collection c', 'a.user_id = c.uid && c.to_uid = a.staff_id' )
                ->join( 'longbing_card_count d', 'a.user_id = d.user_id && a.staff_id = d.to_uid','left' )
                ->order( $order[ 'field' ], $order[ 'way' ] )
                ->group( 'a.user_id, a.staff_id' )
                ->paginate( [ 'list_rows' => 10, 'page' => $params[ 'page' ] ] )
                ->toArray();

        }
        //  已成交的客户
        else if ( $params[ 'label_id' ] )
        {
            $data = RadarUserLabel::alias( 'a' )
                ->field( [ 'd.id as b_id', 'd.create_time', 'max(d.create_time) as b_time',
                        'count(d.id) as b_count', 'b.nickName', 'b.avatarUrl', 'b.avatarUrl', 'b.import',
                        'b.gender', 'c.*' ,'b.is_staff']
                )
                ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.user_id', '<>', $userId ],
                        [ 'a.status', '=', 1 ], [ 'label_id', '=', $params[ 'label_id' ] ] ]
                )
                ->join( 'longbing_card_user b', 'a.user_id = b.id' )
                ->join( 'longbing_card_collection c', 'a.user_id = c.uid && c.to_uid = a.staff_id' )
                ->join( 'longbing_card_count d', 'a.user_id = d.user_id && a.staff_id = d.to_uid','left' )
                ->order( $order[ 'field' ], $order[ 'way' ] )
                ->group( 'a.user_id, a.staff_id' )
                ->paginate( [ 'list_rows' => 10, 'page' => $params[ 'page' ] ] )
                ->toArray();

        }
        else
        {
            return $this->success( [] );
        }

        //  处理雷达展示日期
        $data[ 'data' ] = lbHandelRadarDate( $data[ 'data' ], 'b_time' );

        //  处理用户来源
        $data[ 'data' ] = lbHandelRadarSource( $data[ 'data' ] );

        //  client_source 用户来源 1 = 微信小程序 2 = 百度小程序 3 = 支付宝小程序 4 = 抖音小程序
        //  查询手机号
        $tmpArr = [];
        foreach ( $data[ 'data' ] as $index => $item )
        {
            $data[ 'data' ][ $index ][ 'phone' ]         = '';
            $data[ 'data' ][ $index ][ 'client_source' ] = 1;

            $dis = [

                'user_id'  =>  $item['uid'],

                'staff_id' =>  $item['to_uid'],
            ];

            $data['data'][$index]['remark_name'] = Db::name('longbing_card_client_info')->where($dis)->value('name');


            array_push( $tmpArr, $item[ 'uid' ] );

            // 客户列表相关数据
            if ( $params[ 'is_list' ] == 1 )
            {
                //  给客户打的标签
                $labelList = RadarUserLabel::alias( 'a' )
                    ->field( [ 'b.name' ] )
                    ->join( 'longbing_card_label b', 'a.label_id = b.id' )
                    // 注意这里的表明中的label和字段名label_id不一样，因为字段名取名取错了
                    ->where( [ [ 'a.staff_id', '=', $userId ], [ 'a.user_id', '=', $item[ 'uid' ] ],
                            [ 'a.status', '=', 1 ] ]
                    )
                    ->limit( 4 )
                    ->select()
                    ->toArray();

                $data[ 'data' ][ $index ][ 'labelList' ]  = $labelList;
                $data[ 'data' ][ $index ][ 'labelCount' ] = RadarUserLabel::alias( 'a' )
                    ->field( [ 'b.name' ] )
                    ->join( 'longbing_card_label b', 'a.label_id = b.id' )
                    // 注意这里的表明中的label和字段名label_id不一样，因为字段名取名取错了
                    ->where( [ [ 'a.staff_id', '=', $userId ],
                            [ 'a.user_id', '=', $item[ 'uid' ] ],
                            [ 'a.status', '=', 1 ] ]
                    )
                    ->count();

                $eventData = event("StaffCustomerList", $item );
                $eventData = LongbingArr::array_merge($eventData) ;
                //客户类别数据统计区域
                $data[ 'data' ][ $index ]['client_counts'] = $eventData ;

            }

        }
        if ( !empty( $tmpArr ) )
        {
            $tmpArr = array_unique( $tmpArr );

            $list = UserPhone::where( [ [ 'user_id', 'in', $tmpArr ] ] )
                ->field( [ 'user_id', 'phone' ] )
                ->select()
                ->toArray();

            $markList = RadarUserMark::where( [ [ 'user_id', 'in', $tmpArr ] ] )
                ->field( [ 'user_id', 'mark' ] )
                ->select()
                ->toArray();

            $tmpArr     = [];
            $tmpArrMark = [];

            foreach ( $list as $index => $item )
            {
                $tmpArr[ $item[ 'user_id' ] ] = $item[ 'phone' ];
            }

            foreach ( $markList as $index => $item )
            {
                $tmpArrMark[ $item[ 'user_id' ] ] = $item[ 'mark' ];
            }

            foreach ( $data[ 'data' ] as $index => $item )
            {
                if ( isset( $tmpArr[ $item[ 'uid' ] ] ) )
                {
                    $data[ 'data' ][ $index ][ 'phone' ] = $tmpArr[ $item[ 'uid' ] ];
                }

                if ( isset( $tmpArrMark[ $item[ 'uid' ] ] ) )
                {
                    $data[ 'data' ][ $index ][ 'mark' ] = $tmpArrMark[ $item[ 'uid' ] ];
                    if ( $tmpArrMark[ $item[ 'uid' ] ] == 2 && isset( $data[ 'data' ][ $index ][ 'labelCount' ] ) )
                    {
                        $data[ 'data' ][ $index ][ 'labelCount' ] += 1;
                    }
                }
            }
        }

        $data[ 'data' ] = formatDefaultImage( $data[ 'data' ], 'avatarUrl', 'avatar', $this->defaultImage );

        return $this->success( $data );

    }




    /**
     * @Purpose: 员工端雷达访客AI分析
     *
     * @Method: GET
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function clientAiAnalysis ()
    {
        $userId = $this->getUserId();

        $verify = [ 'client_id' => 'required','staff_id'=>0 ];

        $params = lbGetParamVerify( $this->_param, $verify );
        if(!empty($params['staff_id'])&&$params['staff_id'] !=0){
            $userId = $params['staff_id'];
        }

       // //  客户兴趣占比
        //$data[ 'interest' ] = $this->modelCount->interest( $params[ 'client_id' ], $userId, $this->_uniacid );

        $autlList = AdminMenu::getAuthList(intval($this->_uniacid));



        $client_id =  $params[ 'client_id' ] ;
        $uniacid = $this->_uniacid ;

        $total = 0 ;

        //排除系统模块
        $outModel = ['survey' , 'admin' ];

        foreach ($autlList as $key=> $item ) {

            if(in_array( $key , $outModel)){
                continue ;
            }
            //需要判断文件是否存在
            $infoPath =  APP_PATH . $key . '/info/Info.php' ;
            $dataPath =  APP_PATH . $key . '/info/RadarMessage.php' ;
            if( file_exists($dataPath) ){
                $msgData =  include $dataPath ;
                //替换文字
                $msgData =  changeRadarMsg($msgData,$this->_uniacid);

                $infoData = include $infoPath ;
                $whereAttr  = [] ;
                foreach ($msgData as $msg){
                    $whereAttr[$msg['sign']][] =  $msg['type'] ;
                }

                $whereor = [];
                foreach ($whereAttr as $k => $value){
                    $whereorOn = [] ;
                    $whereorOn[] = ['type' , 'in' , $value] ;
                    $whereorOn[] = ['sign' , '=' , $k] ;
                    $whereor[] =  $whereorOn;
                }

                $radarCountModel = new RadarCount();

                $count = $radarCountModel->where([
                    [ 'user_id', '=', $client_id ],
                    [ 'to_uid', '=', $userId ] ,
                    [ 'uniacid ' , '=' ,  $uniacid ]
                ])->where(function ($query) use($whereor){
                    $query->whereOr($whereor);
                })->count();
                //替换文字
                if($key=='website'){
                    $web_name = tabbarName(4,$this->_uniacid);
                    $infoData['title']  = !empty($web_name)?$web_name:$infoData['title'];
                }
                $total += $count;
                $data[ 'interest' ][] = [
                    'data' =>  $count ,
                    'name' => $infoData['title'],
                    'rate'=> '',
                ];
            }

        }

        //重新计算百分百

        foreach ( $data[ 'interest' ] as $index => $item )
        {
            $number                   = $item[ 'data' ];

            if ($total == 0)
            {
                $rate  = 0;
            }
            else
            {
                $rate  = $number / $total * 100;
            }

            $rate   = sprintf( "%.0f", $rate );
            $data[ 'interest' ][ $index ][ 'rate' ] = $rate;
        }



        //  近15日客户活跃度
        list ( $data[ 'active' ], $data[ 'active_max' ] ) = $this->modelCount->active( $params[ 'client_id' ], $userId, $this->_uniacid );
        //  客户与我的互动
        $data[ 'interaction' ] = $this->modelCount->interaction( $params[ 'client_id' ], $userId, $this->_uniacid );





        return $this->success( $data );
    }











}


